package com.xuya.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DBHelp<T> {
	private String S = "com.mysql.jdbc.Driver";
	private String USER = "root";
	private String PWD = "root";
	private String URL = "jdbc:mysql://localhost:3306/mydb";
	public Connection getConnection(){
		Connection conn = null;
		try {
			
			
			
			Class.forName(S);
			conn = DriverManager.getConnection(URL,USER,PWD);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;	
	}
	public void close(PreparedStatement sta,Connection conn){
		close(null,sta,conn);
		
	}
	public void close(ResultSet res,PreparedStatement sta,Connection conn){
		try {
			if(res != null){
				res.close();
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(sta != null){
					sta.close();
				}
				
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					if(conn != null){
						conn.close();
					}
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}	
	}
	public boolean executeSQL(String sql,Object...args){
		PreparedStatement sta = null;
		Connection conn = getConnection();
		try {
			sta = conn.prepareStatement(sql);
			for(int i = 0;i<args.length;i++){
				sta.setObject(i+1, args[i]);
			}
			int row = sta.executeUpdate();
			if(row>0){
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close(sta, conn);
		}
		return false;
	}
	public T executeForObject(String sql,RowMapper<T> row,Object...args){
		PreparedStatement sta = null;
		Connection conn = getConnection();
		ResultSet res = null;
		T t = null;
		try {
			sta = conn.prepareStatement(sql);
			for(int i = 0;i<args.length;i++){
				sta.setObject(i+1, args[i]);
			}
			res = sta.executeQuery();
			while(res.next()){
				t = row.mapperRow(res);
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close(res,sta, conn);
		}
		return t;
	}
	public List<T> executeForList(String sql,RowMapper<T> row,Object...args){
		PreparedStatement sta = null;
		Connection conn = getConnection();
		ResultSet res = null;
		T t = null;
		List<T> list = new ArrayList<T>();
		try {
			sta = conn.prepareStatement(sql);
			for(int i = 0;i<args.length;i++){
				sta.setObject(i+1, args[i]);
			}
			res = sta.executeQuery();
			while(res.next()){
				t = row.mapperRow(res);
				list.add(t);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			close(res,sta,conn);
		}
		return list;
	}
}
